package com.mao.service;

import com.mao.dao.CommentRepository;
import com.mao.entity.Comment;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by kechelle on 2020/8/18 18:44
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        Sort sort = Sort.by(Sort.Direction.ASC,"createTime");
        List<Comment> comments = commentRepository.findByBlogIdAndParentCommentNull(blogId,sort);
        return eachComment(comments);
    }

    /**
     * 循环每个顶级的评论节点
     * @param comments
     * @return
     */
    private List<Comment> eachComment(List<Comment> comments) {
        List<Comment> commentView = new ArrayList<>();
        for (Comment comment:comments){
            Comment c = new Comment();
            BeanUtils.copyProperties(comment,c);
            commentView.add(c);
        }
        //合并评论的各层子节点到第一层子代集合中
        combineChildren(commentView);
        return commentView;
    }

    /**
     *
     * @param comments root根节点，blog不为空的对象集合
     */
    private void combineChildren(List<Comment> comments) {
        for (Comment comment:comments){
            List<Comment> replyComments = comment.getReplyComments();
            for (Comment reply:replyComments){
                //循环 迭代，找出子代，并存放在tempList中
                recursively(reply);
            }
            //修改顶级节点的reply集合为迭代处理后的集合
            comment.setReplyComments(tempList);
            //清除临时存放区
            tempList = new ArrayList<>();
        }
    }

    //存放迭代找出的所有子代集合
    private List<Comment> tempList = new ArrayList<>();

    /**
     * 递归迭代，剥洋葱
     * @param comment
     */
    private void recursively(Comment comment) {
        tempList.add(comment);  //顶节点添加到临时存放集合
        if (comment.getReplyComments().size()>0){
            List<Comment> replyComments = comment.getReplyComments();
            for (Comment reply:replyComments){
                tempList.add(reply);
                if (reply.getReplyComments().size()>0){
                    recursively(reply);
                }
            }
        }
    }

    @Override
    public Comment saveComment(Comment comment) {
        Long parentCommentId = comment.getParentComment().getId();
        if (parentCommentId != -1){
            comment.setParentComment(commentRepository.getOne(parentCommentId));
        }else {
            comment.setParentComment(null);
        }
        comment.setCreateTime(new Date());
        return commentRepository.save(comment);
    }
}
